package com.xingongchang.baolebei.activity;

import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.external.androidquery.callback.AjaxStatus;
import com.external.maxwin.view.XListView;
import com.external.maxwin.view.XListView.IXListViewListener;
import com.iflytek.speech.RecognizerResult;
import com.iflytek.speech.SpeechError;
import com.iflytek.ui.RecognizerDialog;
import com.iflytek.ui.RecognizerDialogListener;
import com.insthub.BeeFramework.activity.BaseActivity;
import com.insthub.BeeFramework.adapter.BeeBaseAdapter;
import com.insthub.BeeFramework.model.BusinessResponse;
import com.insthub.BeeFramework.view.ToastView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.umeng.analytics.MobclickAgent;
import com.xingongchang.baolebei.BaolebeiManager;
import com.xingongchang.baolebei.R;
import com.xingongchang.baolebei.adapter.ProductListAdapter;
import com.xingongchang.baolebei.model.GoodsListModel;
import com.xingongchang.baolebei.model.ProtocolConst;
import com.xingongchang.baolebei.model.ShoppingCartModel;
import com.xingongchang.baolebei.protocol.FILTER;
import com.xingongchang.baolebei.protocol.PAGINATED;

public class ProductListActivity extends BaseActivity implements
		BusinessResponse, IXListViewListener, OnClickListener
{
	private ImageView backImageButton;
	private ImageView shopping_cart;
	private TextView good_list_shopping_cart_num;
	private LinearLayout good_list_shopping_cart_num_bg;

	private XListView goodlistView;
	private GoodsListModel dataModel;
	private ProductListAdapter listAdapter;

	private boolean isSetAdapter = true;

	private SharedPreferences shared;
	private SharedPreferences.Editor editor;
	private View null_pager;

	public static final String KEYWORD = "keyword";
	public static final String CATEGORY_ID = "category_id";
	public static final String TITLE = "title";
	public static final String FILTER = "filter";

	public static final int IS_HOT = 0;
	public static final int PRICE_DESC_INT = 1;
	public static final int PRICE_ASC_INT = 2;
	public static final int TIME_DESC_INT = 3;
	public static final int TIME_ASC_INT = 4;
	public static final int SALE_DESC_INT = 5;
	public static final int SALE_ASC_INT = 6;
	private int flag_price = PRICE_ASC_INT; // 默认是价格升序排序
	private int flag_time = TIME_DESC_INT; // 默认是时间倒序排序
	private int flag_sale = SALE_DESC_INT; // 默认是销量降序排序

	public String predefine_category_id;
	public TextView product_name;
	private String name;
	NetworkInfo mobNetInfo;
	NetworkInfo wifiNetInfo;
	NetworkInfo mNetworkInfo;// 判断网络是否连接
	private ImageLoader imageLoader = ImageLoader.getInstance();

	protected class TitleCellHolder
	{
		public ImageView arrowImageView; // 箭头
		public TextView titleTextView; // 文字
		public RelativeLayout tabRelative; // 按钮relativelayout
	}

	TitleCellHolder tabOneCellHolder;
	TitleCellHolder tabTwoCellHolder;
	TitleCellHolder tabThreeCellHolder;
	TitleCellHolder tabFourCellHolder;

	private BeeBaseAdapter currentAdapter;

	FILTER filter = new FILTER();

	public ProductListActivity()
	{

	}

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{

		super.onCreate(savedInstanceState);
		setContentView(R.layout.product_list);
		imageLoader.init(ImageLoaderConfiguration.createDefault(this));
		product_name = (TextView) findViewById(R.id.product_name);
		Intent intent = getIntent();
		name = intent.getStringExtra("name");
		product_name.setText(name);
		shared = getSharedPreferences("userInfo", 0);
		editor = shared.edit();
		// 判断是否连接网络
		ConnectivityManager mConnectivityManager = (ConnectivityManager) ProductListActivity.this
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
		mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
		mobNetInfo = mConnectivityManager
				.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
		if (mNetworkInfo == null)
		{
				ToastView toast = new ToastView(this, "网络异常，请检查网络设置");
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();
		}
		backImageButton = (ImageView) findViewById(R.id.search_back);
		backImageButton.setVisibility(View.VISIBLE);
		backImageButton.setOnClickListener(new View.OnClickListener()
		{
			public void onClick(View v)
			{
				InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				finish();
				overridePendingTransition(R.anim.push_left_in,
						R.anim.push_left_out);
			}
		});

		shopping_cart = (ImageView) findViewById(R.id.good_list_shopping_cart);
		shopping_cart.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				String uid = shared.getString("uid", "");
				if (uid.equals(""))
				{
					Intent intent = new Intent(ProductListActivity.this,
							SigninActivity.class);
					startActivity(intent);
					overridePendingTransition(R.anim.push_buttom_in,
							R.anim.push_buttom_out);
					Resources resource = (Resources) getBaseContext()
							.getResources();
					String nol = resource.getString(R.string.no_login);
					ToastView toast = new ToastView(ProductListActivity.this,
							nol);
					toast.setGravity(Gravity.CENTER, 0, 0);
					toast.show();
				} else
				{
					Intent it = new Intent(ProductListActivity.this,
							ShoppingCartActivity.class);
					startActivity(it);
				}
			}
		});
		good_list_shopping_cart_num = (TextView) findViewById(R.id.good_list_shopping_cart_num);
		good_list_shopping_cart_num_bg = (LinearLayout) findViewById(R.id.good_list_shopping_cart_num_bg);
		if (mNetworkInfo != null)
		{
			if (ShoppingCartModel.getInstance().goods_num == 0)
			{
				good_list_shopping_cart_num_bg.setVisibility(View.GONE);
			} else
			{
				good_list_shopping_cart_num_bg.setVisibility(View.VISIBLE);
				good_list_shopping_cart_num
						.setText(ShoppingCartModel.getInstance().goods_num + "");
			}
		}
		null_pager = findViewById(R.id.null_pager);

		goodlistView = (XListView) findViewById(R.id.goods_listview);

		goodlistView.setPullLoadEnable(true);
		goodlistView.setRefreshTime();
		goodlistView.setXListViewListener(this, 1);

		dataModel = new GoodsListModel(this);

		String filter_string = getIntent().getStringExtra(FILTER);
		if (null != filter_string)
		{
			try
			{
				JSONObject filterJSONObject = new JSONObject(filter_string);
				filter = com.xingongchang.baolebei.protocol.FILTER
						.fromJson(filterJSONObject);
				// filter.sort_by = dataModel.IS_HOT;

				if (null != filter.category_id)
				{
					predefine_category_id = filter.category_id;
				}

				if (null != filter.keywords)
				{
					// input.setText(filter.keywords);
				}

			} catch (JSONException e)
			{
				e.printStackTrace();
			}
		}

		dataModel.addResponseListener(this);

		tabOneCellHolder = new TitleCellHolder();
		tabTwoCellHolder = new TitleCellHolder();
		tabThreeCellHolder = new TitleCellHolder();
		tabFourCellHolder = new TitleCellHolder();

		tabOneCellHolder.titleTextView = (TextView) findViewById(R.id.defult_text);
		tabOneCellHolder.tabRelative = (RelativeLayout) findViewById(R.id.tab_defult);
		tabOneCellHolder.tabRelative
				.setOnClickListener(new View.OnClickListener()
				{
					@Override
					public void onClick(View v)
					{
						selectedTab(IS_HOT);
						tabOneCellHolder.titleTextView
								.setTextColor(getResources().getColor(
										R.color.title_select));
						tabTwoCellHolder.titleTextView
								.setTextColor(getResources().getColor(
										R.color.title_custom));
						tabThreeCellHolder.titleTextView
								.setTextColor(getResources().getColor(
										R.color.title_custom));
						tabFourCellHolder.titleTextView
								.setTextColor(getResources().getColor(
										R.color.title_custom));
					}
				});

		tabTwoCellHolder.titleTextView = (TextView) findViewById(R.id.sales_text);
		tabTwoCellHolder.arrowImageView = (ImageView) findViewById(R.id.order_sales);
		tabTwoCellHolder.tabRelative = (RelativeLayout) findViewById(R.id.tab_sales);
		tabTwoCellHolder.tabRelative
				.setOnClickListener(new View.OnClickListener()
				{
					@Override
					public void onClick(View v)
					{
						tabOneCellHolder.titleTextView
								.setTextColor(getResources().getColor(
										R.color.title_custom));
						tabTwoCellHolder.titleTextView
								.setTextColor(getResources().getColor(
										R.color.title_select));
						tabThreeCellHolder.titleTextView
								.setTextColor(getResources().getColor(
										R.color.title_custom));
						tabFourCellHolder.titleTextView
								.setTextColor(getResources().getColor(
										R.color.title_custom));
						if (flag_sale == SALE_DESC_INT)
						{
							selectedTab(SALE_DESC_INT);
							flag_sale = SALE_ASC_INT;
							tabTwoCellHolder.arrowImageView
									.setImageResource(R.drawable.order_down);

						} else if (flag_sale == SALE_ASC_INT)
						{
							selectedTab(SALE_ASC_INT);
							flag_sale = SALE_DESC_INT;
							tabTwoCellHolder.arrowImageView
									.setImageResource(R.drawable.order_up);
						}
					}
				});

		tabThreeCellHolder.titleTextView = (TextView) findViewById(R.id.price_text);
		tabThreeCellHolder.arrowImageView = (ImageView) findViewById(R.id.order_price);
		tabThreeCellHolder.tabRelative = (RelativeLayout) findViewById(R.id.tab_price);
		tabThreeCellHolder.tabRelative
				.setOnClickListener(new View.OnClickListener()
				{
					@Override
					public void onClick(View v)
					{
						tabOneCellHolder.titleTextView
								.setTextColor(getResources().getColor(
										R.color.title_custom));
						tabTwoCellHolder.titleTextView
								.setTextColor(getResources().getColor(
										R.color.title_custom));
						tabThreeCellHolder.titleTextView
								.setTextColor(getResources().getColor(
										R.color.title_select));
						tabFourCellHolder.titleTextView
								.setTextColor(getResources().getColor(
										R.color.title_custom));
						if (flag_price == PRICE_DESC_INT)
						{
							selectedTab(PRICE_DESC_INT);
							flag_price = PRICE_ASC_INT;
							tabThreeCellHolder.arrowImageView
									.setImageResource(R.drawable.order_down);

						} else if (flag_price == PRICE_ASC_INT)
						{
							selectedTab(PRICE_ASC_INT);
							flag_price = PRICE_DESC_INT;
							tabThreeCellHolder.arrowImageView
									.setImageResource(R.drawable.order_up);
						}
					}
				});

		tabFourCellHolder.titleTextView = (TextView) findViewById(R.id.time_text);
		tabFourCellHolder.arrowImageView = (ImageView) findViewById(R.id.order_time);
		tabFourCellHolder.tabRelative = (RelativeLayout) findViewById(R.id.tab_time);
		tabFourCellHolder.tabRelative
				.setOnClickListener(new View.OnClickListener()
				{
					@Override
					public void onClick(View v)
					{
						selectedTab(TIME_ASC_INT);
						tabOneCellHolder.titleTextView
								.setTextColor(getResources().getColor(
										R.color.title_custom));
						tabTwoCellHolder.titleTextView
								.setTextColor(getResources().getColor(
										R.color.title_custom));
						tabThreeCellHolder.titleTextView
								.setTextColor(getResources().getColor(
										R.color.title_custom));
						tabFourCellHolder.titleTextView
								.setTextColor(getResources().getColor(
										R.color.title_select));
						if (flag_time == TIME_DESC_INT)
						{
							selectedTab(TIME_DESC_INT);
							flag_time = TIME_ASC_INT;
							tabFourCellHolder.arrowImageView
									.setImageResource(R.drawable.order_down);

						} else if (flag_time == TIME_ASC_INT)
						{
							selectedTab(TIME_ASC_INT);
							flag_time = TIME_DESC_INT;
							tabFourCellHolder.arrowImageView
									.setImageResource(R.drawable.order_up);
						}
					}
				});
		isSetAdapter = true;
		dataModel.fetchPreSearch(filter);

		// selectedTab(IS_HOT);

	}

	void selectedTab(int index)
	{
		isSetAdapter = true;

		if (index == IS_HOT)
		{

			filter.sort_by = dataModel.IS_HOT;
			dataModel.fetchPreSearch(filter);

		} else if (index == PRICE_DESC_INT)
		{
			filter.sort_by = dataModel.PRICE_DESC;
			dataModel.fetchPreSearch(filter);
			;
		} else if (index == PRICE_ASC_INT)
		{

			filter.sort_by = dataModel.PRICE_ASC;
			dataModel.fetchPreSearch(filter);

		} else if (index == TIME_DESC_INT)
		{

			filter.sort_by = dataModel.TIME_DESC;
			dataModel.fetchPreSearch(filter);

		} else if (index == TIME_ASC_INT)
		{

			filter.sort_by = dataModel.TIME_ASC;
			dataModel.fetchPreSearch(filter);
		} else if (index == SALE_ASC_INT)
		{
			filter.sort_by = dataModel.SALES_NUM_ASC;
			dataModel.fetchPreSearch(filter);
		} else if (index == SALE_DESC_INT)
		{
			filter.sort_by = dataModel.SALES_NUM_DESC;
			dataModel.fetchPreSearch(filter);
		}
	}

	public void setContent()
	{

		if (listAdapter == null)
		{

			if (dataModel.simplegoodsList.size() == 0)
			{
				null_pager.setVisibility(View.VISIBLE);
			} else
			{
				null_pager.setVisibility(View.GONE);
				listAdapter = new ProductListAdapter(this,
						dataModel.simplegoodsList);
				goodlistView.setAdapter(listAdapter);
			}

		} else
		{
			null_pager.setVisibility(View.GONE);
			if (isSetAdapter == true)
			{
				listAdapter = new ProductListAdapter(this,
						dataModel.simplegoodsList);
				goodlistView.setAdapter(listAdapter);
			} else
			{
				listAdapter.dataList = dataModel.simplegoodsList;
				listAdapter.notifyDataSetChanged();
			}
		}
		// //设置购物车数量
		if (ShoppingCartModel.getInstance().goods_num == 0)
		{
			good_list_shopping_cart_num_bg.setVisibility(View.GONE);
		} else
		{
			good_list_shopping_cart_num_bg.setVisibility(View.VISIBLE);
			good_list_shopping_cart_num
					.setText(ShoppingCartModel.getInstance().goods_num + "");
		}

	}

	public void OnMessageResponse(String url, JSONObject jo, AjaxStatus status)
			throws JSONException
	{

		if (url.endsWith(ProtocolConst.SEARCH))
		{
			goodlistView.stopRefresh();
			goodlistView.stopLoadMore();
			goodlistView.setRefreshTime();
			if (dataModel.responseStatus.succeed == 1)
			{
				setContent();
			}
			PAGINATED paginated = PAGINATED.fromJson(jo
					.optJSONObject("paginated"));
			if (0 == paginated.more)
			{
				goodlistView.setPullLoadEnable(false);
			} else
			{
				goodlistView.setPullLoadEnable(true);
			}
			System.out.println(dataModel.simplegoodsList.get(0).img.url);
			System.out.println(dataModel.simplegoodsList.get(0).img.small);
			System.out.println(dataModel.simplegoodsList.get(0).img.thumb);
		}

	}

	@Override
	public void onClick(View v)
	{
		switch (v.getId())
		{
		// case R.id.top_view_search:
		// String keyword = input.getText().toString().toString();
		// if (null != keyword && keyword.length() > 0) {
		// ProductListActivity.this.filter.keywords = keyword;
		// dataModel.fetchPreSearch(ProductListActivity.this.filter);
		// } else {
		// ProductListActivity.this.filter.keywords = null;
		// dataModel.fetchPreSearch(ProductListActivity.this.filter);
		// }
		// CloseKeyBoard();
		// break;
		}

	}

	public void showRecognizerDialog()
	{

		RecognizerDialog recognizerDialog = new RecognizerDialog(this, "appid="
				+ BaolebeiManager.getXunFeiCode());
		recognizerDialog.setEngine("sms", null, null);
		recognizerDialog.setListener(new RecognizerDialogListener()
		{
			@Override
			public void onResults(ArrayList<RecognizerResult> results,
					boolean arg1)
			{
				StringBuffer result = new StringBuffer();
				for (RecognizerResult r : results)
				{
					result.append(r.text);
				}
				if (result.length() > 0)
				{
					// input.setText(result.toString().substring(0,
					// result.toString().length() - 1));
				}

			}

			@Override
			public void onEnd(SpeechError arg0)
			{
				// if (input.getText().toString().equals("")) {
				// ToastView toast = new ToastView(ProductListActivity.this,
				// getString(R.string.you_did_not_speak));
				// toast.setGravity(Gravity.CENTER, 0, 0);
				// toast.show();
				// } else {
				// ProductListActivity.this.filter.keywords = input.getText()
				// .toString();
				// dataModel.fetchPreSearch(ProductListActivity.this.filter);
				// }

			}
		});
		recognizerDialog.show();

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)
	{
		if ((keyCode == KeyEvent.KEYCODE_BACK))
		{
			finish();
			overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
			return false;
		}
		return true;
	}

	@Override
	public void onRefresh(int id)
	{
		isSetAdapter = true;
		dataModel.fetchPreSearch(filter);

	}

	@Override
	public void onLoadMore(int id)
	{
		isSetAdapter = false;
		dataModel.fetchPreSearchMore(filter);
	}

	public void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		switch (requestCode)
		{
		case 1:
		{
			if (null != data)
			{
				String filter_string = data.getStringExtra("filter");
				if (null != filter_string)
				{
					try
					{
						JSONObject filterJSONObject = new JSONObject(
								filter_string);
						FILTER filter = com.xingongchang.baolebei.protocol.FILTER
								.fromJson(filterJSONObject);
						this.filter.category_id = filter.category_id;
						this.filter.price_range = filter.price_range;
						this.filter.brand_id = filter.brand_id;
						dataModel.fetchPreSearch(this.filter);
					} catch (JSONException e)
					{
						e.printStackTrace();
					}
				}
			}
		}

		}
	}

	@Override
	protected void onResume()
	{
		super.onResume();
		if (BaolebeiManager.getUmengKey(this) != null)
		{
			MobclickAgent.onResume(this, BaolebeiManager.getUmengKey(this), "");
			MobclickAgent.onPageStart("FilterPage");
		}
		if (mNetworkInfo != null)
		{
			if (ShoppingCartModel.getInstance().goods_num == 0)
			{
				good_list_shopping_cart_num_bg.setVisibility(View.GONE);
			} else
			{
				good_list_shopping_cart_num_bg.setVisibility(View.VISIBLE);
				good_list_shopping_cart_num
						.setText(ShoppingCartModel.getInstance().goods_num + "");
			}
		}
	}

	// 关闭键盘
	public void CloseKeyBoard()
	{
		// input.clearFocus();
		// InputMethodManager imm = (InputMethodManager)
		// getSystemService(Context.INPUT_METHOD_SERVICE);
		// imm.hideSoftInputFromWindow(input.getWindowToken(), 0);
	}

	@Override
	protected void onDestroy()
	{
		super.onDestroy();
	}

	@Override
	protected void onPause()
	{
		super.onPause();
		if (BaolebeiManager.getUmengKey(this) != null)
		{
			MobclickAgent.onPageEnd("FilterPage");
			MobclickAgent.onPause(this);
		}

	}
}
